package com.example.hotHub.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;


@Slf4j
@Component
public class RestTemplateUtil {

    RestTemplate restTemplate = new RestTemplate();

    public HttpEntity<String> generatePostJson(JSONObject params, String token) {

        //如果需要其它的请求头信息、都可以在这里追加
        HttpHeaders headers = new HttpHeaders();

        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");

        headers.setContentType(type);

        if (token != null) {
            headers.set("Authorization", token);
        }

        HttpEntity<String> httpEntity = new HttpEntity<>(params == null ? null : params.toString(), headers);

        return httpEntity;
    }

    public String doPost(String url, JSONObject params, String token) {

        ResponseEntity<String> apiResponse = restTemplate.postForEntity
                (
                        url,
                        generatePostJson(params, token),
                        String.class
                );
        return apiResponse.getBody();
    }

    public <T> T doGet(String url, Map<String,Object> params, String token, Class<T> clazz){

        HttpHeaders headers = new HttpHeaders();
        headers.set("contentType", "application/json;charset=UTF-8");

        if(token != null) {
            headers.set("Authorization", token);
        }

        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(null, headers);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

        if(params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                builder.queryParam(param.getKey(),param.getValue());
            }
        }

//        log.info("send request to " + builder.build().toUriString());
        Object body = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, request, Object.class).getBody();
        T value = JSONObject.parseObject(JSON.toJSONString(body), clazz);
        return value;
    }

    public <T> T getUrlWithParams(String url, Map<String, String> params, Class<T> clazz) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String body = responseEntity.getBody();
        T value = JSONObject.parseObject(JSON.toJSONString(body), clazz);
        return value;
    }

}
